package com.gg.goods;

import com.gg.entity.Fruit;
import com.gg.helper.DBHelper;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "GetAllFruitsServlet", value = "/goods/GetAllFruitsServlet")
public class GetAllFruitsServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /*创建一个Fruit 集合*/
        List<Fruit> fruits =  new ArrayList<>();
        /*1.数据库 连接*/
        Connection  con = DBHelper.getConnection();
        String priceParam = request.getParameter("price");
        /*2. SQL */
        /*3. 发射器*/
            try {
                // 根据 priceParam 的值构建不同的 SQL 查询
                String sql;
                if ("a".equals(priceParam)) {
                    sql = "SELECT * FROM fruit WHERE f_price < 100";
                } else if ("b".equals(priceParam)) {
                    sql = "SELECT * FROM fruit WHERE f_price BETWEEN 100 AND 300";
                } else if ("c".equals(priceParam)) {
                    sql = "SELECT * FROM fruit WHERE f_price > 300";
                } else {
                    // 如果没有指定 price 参数，查询所有水果
                    sql = "SELECT * FROM fruit";
                }
                PreparedStatement ps = con.prepareStatement(sql);
            ResultSet rs = ps.executeQuery();
            while(rs.next()){
                int  f_id = rs.getInt("f_id");
                String  f_name = rs.getString("f_name");
                String  f_norm = rs.getString("f_norm");
                BigDecimal f_price = rs.getBigDecimal("f_price");
                String  f_summary = rs.getString("f_summary");
                String  f_prompt = rs.getString("f_prompt");
                int  f_imgcount = rs.getInt("f_imgcount");
                String  c_id = rs.getString("c_id");
                boolean  f_entrance = rs.getBoolean("f_entrance");
                boolean  f_hot = rs.getBoolean("f_hot");
                //恢复一个水果
                Fruit fruit =  new Fruit(f_id,f_name,f_norm,f_price,f_summary,f_prompt,f_imgcount,c_id,f_entrance,f_hot);
                //把这个恢复出来的水果放集合里
                fruits.add(fruit);
            }
            /*把20个水果的   集合fruits 放Session里， 跳转页面到sel.jsp页面显示*/
            request.getSession().setAttribute("fruits",fruits);
            response.sendRedirect("/fruit/sel.jsp");
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }


}
